const axios = require("axios");
const {appKey,appSecret} =require('../config/index')
const crypto=require('crypto')
const query = require('../mysql');      //这个是封装的查询数据库的方法
const secret ='qiaopihua_2021_08'
const algorithm='aes-256-cbc'
//请求微信接口，获取对应的openId
const getSession= async function(code){
    const url=`https://api.weixin.qq.com/sns/jscode2session?appid=${appKey}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
    return new Promise(async (resolve,reject)=>{
        try {
            const res=await axios.get(url)
            if(res.data.errcode){
                reject(new Error(res.errmsg))
            }else{
                console.log("+++直接获取到的+++",res.data)
                resolve(res.data)
            }
        } catch (error) {
            reject(error)
        }
    })
}
//取到openId之后用来登陆
const login=async function(code,name){
    //获取openid和sessionkey
    const res=await getSession(code)
    if(res){
        //利用openid查询数据库，看数据库中是否已经有该用户，没有的话，就新建该用户，并保存session_key
        getUserExit(res.openid,name,res.session_key)
        return res
    }else{
        throw new Error('登陆失败')
    }
}
//查询是否是已经注册的用户，没有则创建新用户
async function getUserExit(openid,name,key) {
    let searchSql = `select * from user where openid='${openid}'`;
    let result = await query(searchSql);
    console.log("查询的结果:",result)
    if(result.length==0){
        //创建新的用户
        let sql ="INSERT INTO user (openid,name,session_key) VALUES(?,?,?)"
        var queryParams=[openid,name,key]
        try {
            await query(sql,queryParams)
            console.log("成功创建新的用户")
        } catch (error) {
            throw new Error('创建新的用户失败')
        }
    }else{
        return
    }
}
//登陆
async function originLogin(ctx) {
    const code= ctx.query.code;
    const name= ctx.query.name;
    const res=await login(code,name)
    console.log("测试数据的值",res)
    let json = {
        success:true,
        data:{
            code:'10000',
            session:res
        },
		query:code
    };
    ctx.response.body = json;
}
module.exports={
    originLogin
}